// import music from "../../assets/music";
import dayjs from "../../../../utils/dayjs";
const kugou = require('../../../../utils/kugouMusic');
const app = getApp();
const backgroundAudioManager = wx.getBackgroundAudioManager();
// pages/music/music.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    music: [],
    page: 0,
    tolower: false,
    noMore: false,
    isPlay: false,
    current: {},
    currentIndex: 0,
    hide: app.globalData.hide,
    totalTime: 0, //总时长
    max: 0, //滑块最大值
    value: 0, //进度条进程
    currentTime: 0, //当前时长
    flag: false, //是否在拖动滑块
    showDrawer: false,
    scrollTop: 0,
    myTimeout: null,
    myInterval: null,
    current_music_list: []
  },

  devGoHome() {
    wx.switchTab({
      url: "/pages/index/index",
    });
    wx.showTabBar();
  },

  setMisic(current) {
    let { myInterval } = this.data;
    clearInterval(myInterval);
    backgroundAudioManager.startTime = 0;
    backgroundAudioManager.currentTime = 0;
    backgroundAudioManager.title = current.title;
    backgroundAudioManager.src = current.src;
    backgroundAudioManager.singer = current.singer;
    backgroundAudioManager.coverImgUrl = current.coverImgUrl;

    // this.playMusicError();

    myInterval = setInterval(() => {
      //判断滑块是否在推动
      if (this.data.flag === false) {
        let a =
          dayjs(backgroundAudioManager.duration * 1000).format("mm:ss") ||
          "00:00"; //总时长 用dayjs对总时长进行处理
        let b = parseInt(backgroundAudioManager.duration); //滑块最大值
        let c =
          dayjs(backgroundAudioManager.currentTime * 1000).format("mm:ss") ||
          "00:00"; //当前时长
        let d = parseInt(backgroundAudioManager.currentTime); //滑块值

        this.setData({
          totalTime: a, ///总时长 对数据进行处理后
          max: b, //滑块最大数
          currentTime: c,
          value: d,
        });

        app.globalData.totalTime = a;
        app.globalData.max = b;
        app.globalData.currentTime = c;
        app.globalData.value = d;
        app.globalData.isPlay = true;
      }
    }, 1000);

    // this.nextMusicAutoPlay();

  },

  closeMusic() {
    const { current } = this.data;
    backgroundAudioManager.stop();
    backgroundAudioManager.onStop(() => {
      wx.showToast({
        title: "播放器关闭",
        icon: "none",
      });
      this.setData({
        isPlay: false,
        current: {},
      });
    });
  },

  playMusic(e) {
    const that = this;
    const { hash } = e.currentTarget.dataset;
    let { myInterval } = that.data;
    clearInterval(myInterval);

    kugou.infoMusic(hash).then((res) => {
      // console.log(res.data);
      that.setMisic({
        title: res.data.songName,
        src: res.data.url,
        singer: res.data.singerName,
        coverImgUrl: res.data.imgUrl
      });
      that.setData({
        current: {
          imgUrl: res.data.imgUrl,
          songName: res.data.songName,
          singerName: res.data.singerName,
          url: res.data.url
        }
      })
    })
    that.getCurrentMusic();
    that.setData({
      // current,
      isPlay: true,
      showDrawer: false,
      value: 0,
    });
  },

  startMusic() {
    if (!backgroundAudioManager.src) {
      wx.showToast({
        title: "请选择歌曲",
        icon: "none",
      });
      return;
    }
    backgroundAudioManager.play();
    backgroundAudioManager.onPlay(() => {
      app.globalData.isPlay = true;
      this.getCurrentMusic();
      this.setData({
        isPlay: true,
      });
    });
  },

  stopMusic() {
    let { myInterval } = this.data;
    backgroundAudioManager.pause();
    backgroundAudioManager.onPause(() => {
      app.globalData.isPlay = false;
      clearInterval(myInterval);
      this.setData({
        isPlay: false,
      });
    });
  },

  //  切换歌曲
  changeMusic(e) {
    const { type } = e.currentTarget.dataset;
    let { music, currentIndex, current, myTimeout } = this.data;
    clearTimeout(myTimeout);
    if (type == "prevMusic") {
      currentIndex--;
    } else if (type == "nextMusic") {
      currentIndex++;
    }
    if (currentIndex < 0) {
      currentIndex = music.length - 1;
    } else if (currentIndex > music.length - 1) {
      currentIndex = 0;
    }
    current = music[currentIndex];

    this.setData({
      current,
      currentIndex,
      isPlay: true,
      value: 0,
    });

    this.setMisic(current);
  },

  //滑动拖动完成后执行
  changeSlider(e) {
    // console.log("拖动后", e.detail.value);
    let a = e.detail.value;
    this.setData({
      flag: false,
    });
    backgroundAudioManager.seek(a);
    backgroundAudioManager.play();
  },
  //拖动滑块中
  changingSlider(e) {
    // console.log("滑块中", e.detail.value);
    let b = e.detail.value;
    let a = dayjs(b * 1000).format("mm:ss");
    // console.log(a)
    this.setData({
      currentTime: a,
      flag: true,
    });
  },

  toggleDrawer() {
    this.setData({
      showDrawer: !this.data.showDrawer,
    });
  },

  goToTop() {
    this.setData({
      scrollTop: 0,
    });
  },

  //   自动播放模式
  autoPlayMode() {
    wx.showToast({
      title: "敬请期待",
      icon: "none",
    });
  },

  // 播放下一首
  playNextMusic() {
    let { currentIndex, music, current } = this.data;
    currentIndex++;
    if (currentIndex > music.length - 1) {
      currentIndex = 0;
    }
    current = music[currentIndex];
    this.setData({
      current,
      currentIndex,
      isPlay: true,
    });

    this.setMisic(current);
  },

  // 播放完毕自动下一首
  nextMusicAutoPlay() {
    const that = this;
    backgroundAudioManager.onEnded(() => {
      that.playNextMusic();
    });
  },

  // 歌曲播放失败
  playMusicError() {
    const that = this;
    let { myTimeout } = that.data;
    backgroundAudioManager.onError(() => {
      that.setData({
        totalTime: '00:00',
        currentTime: '00:00'
      })
      wx.showToast({
        title: "播放地址失效，跳转下一首",
        icon: "none",
      });
      myTimeout = setTimeout(() => {
        that.playNextMusic();
      }, 1500);

      that.setData({
        myTimeout,
        isPlay: false,
      });
    });
  },

  refreshMusic() { },

  getCurrentMusic() {
    const that = this;
    let { myInterval } = that.data;
    myInterval = setInterval(() => {
      that.setData({
        totalTime: app.globalData.totalTime,
        max: app.globalData.max,
        currentTime: app.globalData.currentTime,
        value: app.globalData.value,
        isPlay: app.globalData.isPlay,
      })
    }, 1000);
    that.setData({
      myInterval
    });

    backgroundAudioManager.onEnded(() => {
      clearInterval(myInterval);
      app.globalData.isPlay = false;
      app.globalData.totalTime = '00:00';
      app.globalData.currentTime = '00:00';
      that.setData({
        isPlay: false,
        totalTime: '00:00',
        currentTime: '00:00',
      })
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let { current } = options;
    current = JSON.parse(current);
    this.setData({
      current
    })
    this.getCurrentMusic();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let { current_music_list } = this.data;
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#1a1a1a",
      animation: {
        duration: 400,
        timingFunc: "easeIn",
      },
    });
    current_music_list = wx.getStorageSync('current_music_list');
    this.setData({ current_music_list });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    let { myInterval } = this.data;
    clearInterval(myInterval);
    // this.closeMusic()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
  // 分享到朋友圈
  onShareTimeline() { },
});